<?php
/**
 * 提现
 * User: zal
 * Date: 2016/3/19
 * Time: 12:52
 */
namespace Api\Controller;
use Api\Controller\BaseController;

class CashController extends BaseController {

    //状态
    const STATUS_AL         =   1;      // 已处理
    const STATUS_UN       =   0;      // 未处理

    //最低提现额
    static protected $min       =  0;

    //加载配置项
     public function __construct() {
        parent::_initialize();
        self::$min=C("site_cash_min_money");//利息年化率
    }

    public function index(){
        //解决跨域
        echoHeader();
        $user_id=I('get.user_id','');
        $page=I('get.page','1'); //页码
        $size=I('get.size','10'); //显示数目
        $userData=$this->checkUserIsExist($user_id);
        if(isset($userData["code"])){
            $this->ajaxReturn($userData,'JSON');
        }
        $users=$userData["user"];
        $map["ca.user_id"]=$user_id;
        $limit_txt="";
        if($page>=1){
            $limit_txt=$size * ($page - 1).",".$size;
        }else{
            $limit_txt=$size;
        }
        $cashList=M('Cash')->join('as ca left join zsf_bank_card as bc on ca.bcid=bc.id left JOIN zsf_bank_list as bl ON bc.bank_id = bl.bank_id' )
            ->field("ca.id,bl.bank_name,bc.bank_num,ca.money,ca.status,ca.add_time,ca.update_time,bc.isdefault,ca.user_id")
            ->where($map)->order('id desc')->limit($limit_txt)->select();
        $dataList=array();
        foreach($cashList as $key=>$val){
            $bank_num=$val["bank_num"];
            $bank_num=substr($bank_num,strlen($bank_num)-4,strlen($bank_num));
            $val["bank_num"]=$bank_num;
            $val["add_time"]=date("Y-m-d",$val["add_time"]);
            if($val["status"]==self::STATUS_AL){
                $val["status_name"]="已处理";
            }else{
                $val["status_name"]="处理中";
            }
            if(!empty($val["update_time"])){
                $val["update_time"]=date("Y-m-d H:i:s",$val["update_time"]);
            }
            $dataList[]=$val;
        }

        $data["data"]=$dataList;
        $data["code"]=200;
        $data["msg"]='ok';
        $this->ajaxReturn($data,'JSON');
    }

    /**
     * 跳转到提现页面
     * @return mixed
     */
    public function toCash(){
        //解决跨域
        echoHeader();
        $data=array();
        $user_id=I('get.user_id','');
        $userData=$this->checkUserIsExist($user_id);
        if(isset($userData["code"])){
            $this->ajaxReturn($userData,'JSON');
        }
        $users=$userData["user"];
        $isBankCard=0;//是否设置银行卡
        // $total=$users["total"];//用户余额
        $userMoney=$this->getUserMoney($user_id);

        if(isset($userMoney["code"])){
            $this->ajaxReturn($userMoney,'JSON');
        }

        if($users["is_real"]==0){
            $data["code"]=1013;
            $data["msg"]='您还未实名认证';
            $this->ajaxReturn($data,'JSON');
        }

        if(empty($users["draw_money_pass"])){
            $data["code"]=1016;
            $data["msg"]='您还未设置支付密码';
            $this->ajaxReturn($data,'JSON');
        }

        $map["status"]=0;
        $map["user_id"]=$user_id;
        $cashInfo=M('Cash')->where($map)->find();
        if(!empty($cashInfo)){
            $data["code"]=1015;
            $data["msg"]='您还有未处理的提现记录';
            $this->ajaxReturn($data,'JSON');
        }

        $balance=$userMoney["balance"];
        $bankCardMap["user_id"]=$user_id;
        //是否设置默认提现银行卡
        //$bankCardList=M('BankCard')->where($bankCardMap)->order('id desc')->select();
        $bankCardList = M('BankCard')->join('as bc left JOIN zsf_bank_list as bl ON bc.bank_id = bl.bank_id' )->field("bc.id,bl.bank_name,bc.isdefault,bc.user_id,bc.bank_num")
            ->where($bankCardMap)->order('isdefault desc,id desc')->select();
        if(count($bankCardList)>0){
            $isBankCard=1;
        }
        $dataList=array();
        foreach($bankCardList as $val){
            $bank_num=$val["bank_num"];
            $bank_num=substr($bank_num,strlen($bank_num)-4,strlen($bank_num));
            $val["bank_num"]=$bank_num;
            $dataList[]=$val;
        }

        $data["balance"]=$balance;
        $data["isBankCard"]=$isBankCard;
        $data["bankCardList"]=$dataList;
        $data["code"]=200;
        $data["msg"]='ok';
        $this->ajaxReturn($data,'JSON');
    }

    /**
     * 处理提现操作
     */
    public function doCash(){
        //解决跨域
        echoHeader();
        $user_id=I('post.user_id','');
        $bcid=I('post.bcid','');
        $money=I('post.money','');
        $password=I('post.password','');//支付密码
        $addtime=time();
        $data=array();
        if(empty($bcid)||empty($money)){
            $data["code"]=1001;
            $data["msg"]='缺少参数(提现银行或提现金额不能为空)';
            $this->ajaxReturn($data,'JSON');
        }
        if(empty($password)){
            $data["code"]=1001;
            $data["msg"]='支付密码不能为空';
            $this->ajaxReturn($data,'JSON');
        }
        $userData=$this->checkUserIsExist($user_id);
        if(isset($userData["code"])){
            $this->ajaxReturn($userData,'JSON');
        }
        $users=$userData["user"];
        $random=$users["random"];

        if($users["is_real"]==0){
            $data["code"]=1013;
            $data["msg"]='您还未实名认证';
            $this->ajaxReturn($data,'JSON');
        }

        $userMoney=$this->getUserMoney($user_id);
        if(isset($userMoney["code"])){
            $this->ajaxReturn($userMoney,'JSON');
        }
        $balance=$userMoney["balance"];//用户余额
        if($balance<self::$min){
            $data["code"]=1014;
            $data["msg"]='您的余额必须大于100';
            $this->ajaxReturn($data,'JSON');
        }else if($money<self::$min){
            $data["code"]=1014;
            $data["msg"]='您的提现金额必须大于100';
            $this->ajaxReturn($data,'JSON');
        }else if($money>$balance){
            $data["code"]=1014;
            $data["msg"]='您的提现金额不能超过您的余额';
            $this->ajaxReturn($data,'JSON');
        }

        if($users["draw_money_pass"]!=md5(md5($password).$random)){
            $data["code"]=1012;
            $data["msg"]='支付密码不正确';
            $this->ajaxReturn($data,'JSON');
        }

        $map["status"]=0;
        $map["user_id"]=$user_id;
        $cashInfo=M('Cash')->where($map)->find();
        if(!empty($cashInfo)){
            $data["code"]=1015;
            $data["msg"]='您还有未处理的提现记录';
            $this->ajaxReturn($data,'JSON');
        }

        $cashModel=M('Cash');
        $insetData["user_id"]=$user_id;
        $insetData["bcid"]=$bcid;
        $insetData["money"]=$money;
        $insetData["add_time"]=$addtime;
        $cashModel->startTrans();
        //新增提现记录
        $cash_insert=$cashModel->add($insetData);
        if($cash_insert===false){
            $cashModel->rollback();
            $data["code"]=403;
            $data["msg"]='提现失败';
        }else{
            $yue=$balance-$money;//余额
            if($yue<0){
                $cashModel->rollback();
                $data["code"]=401;
                $data["msg"]='非法操作';
                $this->ajaxReturn($data,'JSON');
            }
            $frozen_total=$userMoney["frozen_total"];//原来冻结资金
            $moenyData["balance"]=$yue;
            $moenyData["frozen_total"]=$frozen_total+$money; //将要更新的冻结资金
            //提现成功后，更新余额和冻结资金
            $result=M('UserMoney')->where('user_id='.$user_id)->save($moenyData);
            if($result!==false){
                //新增账户明细
                $mhMap["user_id"]=$user_id;
                $mhMap["type"]=4;
                $mhMap["total"]=$money;
                $mhMap["is_plus"]=0;
                $mhMap["balance"]=$yue;
                $mhMap['flag'] = 5;
                $mhMap["add_time"]=time();
                $mhMap["remark"]="提现";
                $result=M("MoneyHistory")->add($mhMap);
                //添加失败，回滚用户钱包以及用户提现记录
                if($result===false){
                    $cashModel->rollback();
                    $data["code"]=403;
                    $data["msg"]='提现失败';
                }else{
                    $cashModel->commit();
                    $data["code"]=200;
                    $data["msg"]='ok';
                }
            }else{
                $cashModel->rollback();
                //如果用户钱包更新失败，删除刚才添加的提现记录
                $data["code"]=403;
                $data["msg"]='提现失败';
            }
        }
        $this->ajaxReturn($data,'JSON');
    }

}